<?php

namespace app\models;

use Yii;

/**
 * AccountWechat
 */
class AccountWechat extends \yii\db\ActiveRecord
{
	/**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'account_wechat';
    }

    /**
     * 判断 OpenId 是否已经注册过
     */
    public static function initRecord($params){
    	$open_id  =  isset($params["open_id"]) ? $params["open_id"] : "";
    	$user_open = static::find()->where(['open_id'=>$open_id])->limit(1)->one();
    	if (empty($user_open)) {
    		$user_open = new static();
    		$user_open->open_id = $open_id;
    		$user_open->status = 'ok';
    		$user_open->create_time = date('Y-m-d H:i:s');

    		// 初始化用户账号
    		$account = [
				"nick_name" => isset($params['name']) ? $params['name'] : $open_id,
			];
			$user_open->ff_id = AccountInfo::initRecord($account);
    	}
    	
    	if ($params['wx_id']) {
    		$user_open->wx_id = $params['wx_id'];
    	}
    	if ($params['name']) {
    		$user_open->name = $params['name'];
    	}
    	if ($params['avatar']) {
    		$user_open->avatar = $params['avatar'];
    	}
    	if ($params['country']) {
    		$user_open->country = $params['country'];
    	}
    	if ($params['province']) {
    		$user_open->province = $params['province'];
    	}
    	if ($params['city']) {
    		$user_open->city = $params['city'];
    	}
    	if ($params['language']) {
    		$user_open->language = $params['language'];
    	}
    	if ($params['sex']) {
    		$user_open->sex = $params['sex'];
    	}
    	if ($params['email']) {
    		$user_open->email = $params['email'];
    	}
    	$user_open->save();
    	return $user_open->ff_id;
    }
}